package dao

import (
	"biz_alert/model"
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type BizExceptionDaoInterface interface {
	//GetException 查询业务的异常数据
	GetException() ([]model.BizException, error)
	//Total 总数
	Total() (int, error)
}

type BizExceptionDaoImpl struct {
	db     *gorm.DB
	logger *zap.Logger
}

var NewBizExceptionDaoImpl = func(db *gorm.DB) BizExceptionDaoInterface {
	return &BizExceptionDaoImpl{
		db:     db,
		logger: zap.L().Named("biz_exception"),
	}
}

func (b *BizExceptionDaoImpl) GetException() (bzs []model.BizException, err error) {
	bz := model.BizException{}
	bzs = make([]model.BizException, 0)
	err = b.db.Table(bz.TableName()).Select("*").Find(&bzs).Error
	if err != nil {
		b.logger.Error("query biz_exception err ", zap.Error(err))
		return nil, err
	}
	return bzs, nil
}

func (b *BizExceptionDaoImpl) Total() (int, error) {
	bz := model.BizException{}
	var count int
	err := b.db.Select("count(*)").Table(bz.TableName()).Find(&count).Error
	if err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			b.logger.Error("get biz_exception count err", zap.Error(err))
			return 0, err
		}
	}
	return count, nil
}
